<template>
    <div class="friend-container">
        <!-- 页面标题 -->
        <div class="page-header">
            <h2><el-icon>
                    <User />
                </el-icon> 联系人</h2>
            <el-input v-model="searchKey" placeholder="搜索好友" prefix-icon="el-icon-search" size="small"
                style="width: 200px" clearable />
        </div>

        <!-- 好友列表 -->
        <div class="friend-list">
            <!-- 加载中 -->
            <div v-if="loading" class="loading">
                <el-spin />
            </div>

            <!-- 无数据 -->
            <div v-else-if="filteredFriends.length === 0" class="no-data">
                <el-empty :description="error ? '加载失败，请刷新重试' : '暂无好友'" />
            </div>

            <!-- 好友项 -->
            <div v-for="item in filteredFriends" :key="item.id" class="friend-item" @click="handleChat(item)">
                <el-avatar :size="40" :src="item.avatar || 'https://i.imgur.com/77kRfUI.png'" style="flex-shrink: 0" />
                <div class="info">
                    <div class="name">{{ item.nickname || item.username }}</div>
                    <div class="status">
                        <el-tag size="small" :type="item.online ? 'success' : 'info'" effect="plain">
                            {{ item.online ? '在线' : '离线' }}
                        </el-tag>
                    </div>
                </div>
                <el-button size="small" type="primary" @click.stop="handleChat(item)">
                    发消息
                </el-button>
            </div>
        </div>
    </div>
</template>

<script>
import { getToken } from '@/utils/auth'

export default {
    data() {
        return {
            friends: [],
            searchKey: '',
            loading: false,
            error: null
        };
    },
    computed: {
        // 搜索过滤
        filteredFriends() {
            return this.friends.filter(friend =>
                friend.username?.includes(this.searchKey) ||
                friend.nickname?.includes(this.searchKey)
            );
        }
    },
    mounted() {
        this.loadFriends();
    },
    methods: {
        loadFriends() {
            this.loading = true;
            this.error = null;

            fetch('/api/friends', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': "Bearer " + getToken()
                }
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('获取好友列表失败');
                    }
                    return response.json();
                })
                .then(data => {
                    // 假设后端返回 [{ id: 1, username: 'tom', nickname: '小汤', online: true, avatar: '...' }]
                    this.friends = Array.isArray(data) ? data : [];
                })
                .catch(err => {
                    this.error = err.message;
                    this.$message.error(err.message);
                })
                .finally(() => {
                    this.loading = false;
                });
        },
        handleChat(friend) {
            // 这里可以：
            // 1. 跳转到聊天窗口：this.$router.push(`/chat/${friend.id}`)
            // 2. 打开聊天侧边栏
            // 3. 触发 WebSocket 连接
            this.$message.info(`正在与 ${friend.nickname || friend.username} 聊天`);

            // 示例：跳转到会话页（可后续扩展）
            // this.$router.push(`/chatwindow/conversation?to=${friend.id}`);

            this.$router.push({
                name: 'ChatWindow', // 对应路由中定义的 name
                query: {
                    id: friend.id,
                    nickname: friend.nickname,
                    username: friend.username,
                    avatar: friend.avatar // 如果有头像字段
                }
            });
        }
    }
};
</script>

<style scoped>
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.friend-list {
    min-height: 400px;
}

.friend-item {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    border-bottom: 1px solid #eee;
    transition: background-color 0.2s;
    gap: 12px;
}

.friend-item:hover {
    background-color: #f5f7fa;
    cursor: pointer;
}

.info {
    flex: 1;
    overflow: hidden;
}

.name {
    font-weight: 500;
    color: #333;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.status {
    font-size: 12px;
    color: #999;
    margin-top: 4px;
}

.no-data {
    text-align: center;
    padding: 40px 0;
    color: #999;
}

.loading {
    text-align: center;
    padding: 40px 0;
}
</style>